package com.gitee.wsl.time.wheel

import com.gitee.wsl.collections.deque.Deque
import com.gitee.wsl.collections.deque.link.AbstractLinkedDeque

/**
 * A linked deque implementation used to represent a write-order queue.
 *
 * @author ben.manes@gmail.com (Ben Manes)
 * @param <E> the type of elements held in this collection
</E> */
internal class WriteOrderDeque<E : WriteOrderDeque.WriteOrder<E>> : AbstractLinkedDeque<E>() {

    // A fast-path containment check
    override fun contains(e: E): Boolean {
        return (e.previousInWriteOrder != null)
                || (e.nextInWriteOrder != null)
                || (e === first())
    }

    // A fast-path removal
    override fun remove(e: E): Boolean {
        if (contains(e)) {
            unlink(e)
            return true
        }
        return false
    }


    override fun getPrevious(e: E): E? {
        return e.previousInWriteOrder
    }

    override fun setPrevious(e: E,  prev: E?) {
        e.previousInWriteOrder = prev
    }


    override fun getNext(e: E): E? {
        return e.nextInWriteOrder
    }

    override fun setNext(e: E,  next: E?) {
        e.nextInWriteOrder = next
    }

    /**
     * An element that is linked on the [Deque].
     */
    interface WriteOrder<T : WriteOrder<T>> {
        /** Sets the previous element or `null` if there is no link.  */

        var previousInWriteOrder: T?

        /** Sets the next element or `null` if there is no link.  */
        var nextInWriteOrder: T?
    }
}
